﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace student_systemApp
{
    public partial class UpdateStudentForm : Form
    {
        public UpdateStudentForm()
        {
            InitializeComponent();
        }

        private void UpdateStudentForm_Load(object sender, EventArgs e)
        {
            try
            {
                string studentId = this.Tag.ToString();
                //加载学生信息
                initStudentInfo(studentId);
                initClass();
            }
            catch (Exception ex)
            {
                MessageBox.Show("初始化失败错误提示：" + ex);
            }

        }

        private void initStudentInfo(string studentId)
        {
            if (studentId != null && studentId != "")
            {
                string selectSql = "select * from student where student_id = @studentId";
                string connectionString = ConfigurationManager.ConnectionStrings["UserManagementConnectionString"].ConnectionString;
                using (var connection = new MySqlConnection(connectionString))
                {
                    using (var command = new MySqlCommand(selectSql, connection))
                    {
                        command.Parameters.AddWithValue("@studentId", studentId);
                        connection.Open();
                        using (var reader = command.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                textBox_studentName.Text = reader["student_name"].ToString();
                                //textBox_studentSex.Text = reader["sex"].ToString();
                                string sex = reader["sex"].ToString();
                                if (sex == "M")
                                {
                                    radioButton_man.Checked = true;
                                }
                                else
                                {
                                    radioButton_nv.Checked = true;
                                }
                                textBox_phoneNumber.Text = reader["phone_number"].ToString();
                                int classId = (int)reader["class_id"];
                                comboBox_class.SelectedValue = classId;
                            }
                        }
                    }
                }
            }
        }
        //提交按钮
        private void button_submit_Click(object sender, EventArgs e)
        {
            string updateSql = "update student set student_name = @studentName,sex = @sex,phone_number = @phoneNumber,class_id = @classId where student_id = @studentId";
            string connectionString = ConfigurationManager.ConnectionStrings["UserManagementConnectionString"].ConnectionString;
            using (var connection = new MySqlConnection(connectionString))
            {
                try
                {
                    string studentName = textBox_studentName.Text;
                    int classId = (int)comboBox_class.SelectedValue;
                    string sex = radioButton_man.Checked ? "M" : "F";
                    string phoneNumber = textBox_phoneNumber.Text;

                    if (studentName == "")
                    {
                        MessageBox.Show("请输入学生姓名", "提示");
                        return;
                    }
                    if (phoneNumber == "")
                    {
                        MessageBox.Show("请输入手机号", "提示");
                        return;
                    }

                    // 创建连接
                    connection.Open();
                    using (var command = new MySqlCommand(updateSql, connection))
                    {
                        //添加参数
                        command.Parameters.AddWithValue("@studentId", this.Tag);
                        command.Parameters.AddWithValue("@studentName", studentName);
                        command.Parameters.AddWithValue("@sex", sex);
                        command.Parameters.AddWithValue("@phoneNumber", phoneNumber);
                        command.Parameters.AddWithValue("@classId", classId);

                        //执行命令
                        int result =  command.ExecuteNonQuery();
                        if (result > 0)
                        {
                            MessageBox.Show("更新成功");
                            //提示成功后跨页面刷新，委托
                            //ListStudentForm listStudentForm = new ListStudentForm();
                            //pullMdiForm(listStudentForm);
                            //listStudentForm.Show();
                            returnForm();
                        }
                    }

                }catch (Exception ex)
                {
                    MessageBox.Show("更新失败错误提示：" + ex);
                }
            }
        }
        private void pullMdiForm(Form form)
        {
            form.WindowState = FormWindowState.Normal;

            form.MdiParent = this.ParentForm;

            form.MaximizeBox = false;

            form.Dock = DockStyle.Fill;
        }

        private void button_exit_Click(object sender, EventArgs e)
        {
            returnForm();
        }
        private void initClass()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["UserManagementConnectionString"].ConnectionString;
            string sql = "SELECT class_id,class_name,grade_name from" +
                " class c " +
                "inner join" +
                " grade g on c.grade_id = g.grade_id" +
                " order by g.grade_id ASC";

            using (var connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    MySqlCommand command = new MySqlCommand(sql, connection);
                    MySqlDataAdapter adapter = new MySqlDataAdapter(command);
                    DataTable dt = new DataTable();
                    adapter.Fill(dt);

                    //DataRow row = dt.NewRow();
                    //row["class_name"] = "请选择";
                    //row["class_id"] = 0;
                    //dt.Rows.InsertAt(row, 0);

                    foreach (DataRow dr in dt.Rows)
                    {
                        if ((int)dr["class_id"] != 0) // 跳过默认项
                        {
                            string originalClassName = (string)dr["class_name"];
                            string originalGradeName = (string)dr["grade_name"];
                            dr["class_name"] = originalClassName + "----" + originalGradeName;
                        }
                    }
                    //绑定数据
                    comboBox_class.DataSource = dt;
                    comboBox_class.DisplayMember = "class_name";
                    comboBox_class.ValueMember = "class_id";

                    ////默认选择0
                    //comboBox_class.SelectedIndex = 1;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("查找失败" + ex.Message, "提示");
                }
                connection.Close();
            }
        }
       //返回学生列表界面
        private void returnForm()
        {
            var mainForm = (MainForm)Application.OpenForms["MainForm"];

            if (mainForm != null)
            {
                //this.Close();
                // 创建学生列表窗体
                var listStudentForm = new ListStudentForm();

                // 将子窗体添加到 MDI 父窗体中
                listStudentForm.MdiParent = mainForm;
                //充满整个MDI容器
                pullMdiForm(listStudentForm);

                // 显示学生列表窗体
                listStudentForm.Show();
            }
        }
    }
}
